import logging

from django.shortcuts import render
from django.utils.encoding import escape_uri_path
from django.views import View
from django.conf import settings
from django.http import FileResponse,Http404

import requests

logger = logging.getLogger("django")
from .models import Doc
# Create your views here.


def doc_download(request):
    """
     doc
    """
    docs = Doc.objects.defer("author", "update_time", "create_time", "is_delete").filter(is_delete=False)
    return render(request, "doc/docDownload.html", locals())


class DocView(View):
    """
    doc
    /docs/<int:doc_id>/
    """
    def get(self,request,doc_id):

        doc = Doc.objects.only("file_url").filter(is_delete=False,id=doc_id).first()
        if doc:
            doc_url = doc.file_url
            doc_url = settings.SITE_DOMAIN_PORT +doc_url if not doc_url.startswith('http') else doc_url
            try:
                res = FileResponse(requests.get(doc_url,stream=True)) # stream=True 用的时候再下载,可以极大的节省内存,不需要先全部缓存
                # 测试用
                # res = FileResponse(open(doc.file_url,'rb'))
            except Exception as e:
                logger.info("获取文档异常:\n{}".format(e))
                raise Http404("文档下载异常")

            ex_name = doc_url.split('.')[-1]#获取文件后缀名
            if not ex_name:
                raise Http404("文档url异常")
            else:
                ex_name =ex_name.lower()

            if ex_name == "pdf":
                res["Content-type"] = "application/pdf"
            elif ex_name == "zip":
                res["Content-type"] = "application/zip"
            elif ex_name == "jpg":
                res["Content-type"] = "image/jpeg"
            elif ex_name == "doc":
                res["Content-type"] = "application/msword"
            elif ex_name == "xls":
                res["Content-type"] = "application/vnd.ms-excel"
            elif ex_name == "docx":
                res["Content-type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            elif ex_name == "ppt":
                res["Content-type"] = "application/vnd.ms-powerpoin"
            elif ex_name == "pptx":
                res["Content-type"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"

            else:
                raise Http404("文档格式不正确")

            # 设置浏览器点击后处理方式 http1.1规范
            #attachment不打开 如果设置inline会直接打开 filename下载后的文件名
            # res["Content-Disposition"] = "attachment; filename={}".format(doc_url.split('/')[-1])
            final_filename = doc.title + '.' +ex_name
            # doc_filename = escape_uri_path(doc_url.split('/')[-1])  # 编码 将文件名编码成url格式
            doc_filename = escape_uri_path(final_filename)  # 中文名
            res["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(doc_filename) # 响应头编码utf8
            return res
        else:
            raise Http404("文档不存在")
